import math

from flask import Flask, render_template
from models import db
from.settings import Dev
app = Flask(__name__)

app.config.from_object(settings.Dev)

# 初始化sqlalchemy类对象
db.init_app(app)

def datefmt_fileter(value, *args):
    # 把时间转为字符串
    return value.strftime(args[0])

@app.template_filter('moneyfmt')
def monerfmt_filter(value, method="common",precision=0):
    value = round(value,precision) # 五舍五入
    # 1.
    # 以千位符分隔
    #  'common' 普通的金额的格式化，以千位符分割
    if method == 'common':
        # 1. 只有整数的格式化
        # v = str(value)[::-1]
        # vs = [v[i*3:i*3+3] for i in range(math.ceil(len(v)/3))]
        # return ','.join(vs)[::-1]

        # 2.
        if isinstance(value,int):
            pre_v = str(value)
            end_v = '00'
        else:
            pre_v,end_v = str(value).split('.')
            end_v = "." + end_v
        pre_v = pre_v[::-1]
        vs = [pre_v[i * 3:i * 3 + 3] for i in range(math.ceil(len(pre_v) / 3))]
        return ','.join(vs)[::-1] + end_v

    # 'currency' 货币单位，万、百万、千万、亿
    cur = ''
    if value / 10000 < 1:
        cur = '元'
    elif value / (100*10000) < 1:
        cur = '万元'
        value = round(value / 10000, 2)
    elif value /(1000*10000) < 1:
        cur = '百万元'
        value = round(value / (100*10000), 2)
    elif value /(10000*10000) < 1:
        cur = '千万元'
        value = round(value / (1000*10000), 2)
    else:
        cur = '亿元'
        value = round(value / (10000 * 10000), 2)

    return str(value) + cur

@app.errorhandler(404)
def notfounded(error):
    print(error)
    return render_template('404.html')

@app.errorhandler(500)
def handlerOfError(error):
    print(error)
    return render_template('500.html')